/*
 * Copyright 2012 Andrea Parodi
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package eban.storebyrules;


import com.almworks.sqlite4java.SQLiteConnection;
import com.almworks.sqlite4java.SQLiteException;
import com.almworks.sqlite4java.SQLiteStatement;
import com.google.common.base.Preconditions;
import eban.storebyrules.results.Result;
import eban.storebyrules.results.SqliteAdapter;
import lombok.extern.log4j.Log4j;

import java.io.File;


/**
 * This class is thread confined because
 * it is not thread safe to use. Every method call
 * has as a precondition that its calling thread be
 * the same of the thread in which the instance was called.
 */
@Log4j
public class SqliteStorage extends AbstractStorage {
    private final String dbLocation;

    public AbstractTransaction buildTransaction() {

        AbstractTransaction transaction = new AbstractTransaction(this) {};
        executeInternal("BEGIN TRANSACTION");
        return transaction;
    }
    protected void commitInternal() {
        executeInternal("COMMIT");
    }
    protected void rollbackInternal() {
        executeInternal("ROLLBACK");
    }
    public void dispose() {
        if (connection != null)
            connection.dispose();
    }
    protected Result getResult(String sql) {
        try {
            SQLiteStatement prepare = connection.prepare(sql);
            if (SqliteStorage.log.isDebugEnabled())
                SqliteStorage.log.debug("Executed sql.");

            return new SqliteAdapter(prepare, connection);
        } catch (SQLiteException e) {
            throw new PersistenceException("Unable to execute sql " + sql, e);

        }
    }


    private SqliteStorage(String dbLocation) {
        this.dbLocation = dbLocation;
    }

    public static SqliteStorage newInstance(String dbLocation) {
        return new SqliteStorage(dbLocation);
    }



    public static SqliteStorage newMemoryInstance() {

        return new SqliteStorage(null){
            @Override public Transaction beginTransaction() {
                checkSameThreadAsConstructionTime();
                checkDbExists();
                Preconditions.checkState(currentTransaction == null, "transaction pending");

                currentTransaction = new AbstractTransaction(this,true) {};
                executeInternal("BEGIN TRANSACTION");
                return currentTransaction;


            }
        };
    }


    SQLiteConnection getConnection() {
        return connection;
    }

    private SQLiteConnection connection;

    protected void createConnectionToNewOrExistingStorage() {
        if (connection != null) return;
        try {
            File file = null;
            if (dbLocation != null)
                file = new File(dbLocation);
            SQLiteConnection cn = newConnectionInstance();
            boolean isNewDb=(file == null || !file.exists());
            cn.open(true);
            connection = cn;
            if (isNewDb)
                createTables();


        } catch (Exception e) {
            throw new PersistenceDesignException("Unable to create database", e);
        }
    }

    /*@Override
    public void execute(String sql) {
        checkSameThreadAsConstructionTime();
        currentTransaction.execute(sql);
    }*/
    protected void executeInternal(String sql) {
        try {
            getConnection().exec(sql);
        } catch (SQLiteException e) {
            throw new RuntimeException(e);
        }
    }

    protected SQLiteConnection newConnectionInstance() {
        if (dbLocation == null)
            return new SQLiteConnection();
        return new SQLiteConnection(new File(dbLocation));
    }

    private final static boolean DEBUG = true;


}
